package com.sgcc.pda.apimodel.model;

import android.content.Context;
import android.net.Uri;

import com.sgcc.pda.apimodel.request.ApiGateRequestBean;
import com.sgcc.pda.apimodel.request.PostDataWeaveStringRequest;
import com.sgcc.pda.mdrh.app.ZoomApplication;
import com.sgcc.pda.mvp.model.HzBaseHttpModel;
import com.sgcc.pda.newsm4.SM4Utils;
import com.sgcc.pda.okhttp.bean.OkHttpRequestEntity;
import com.sgcc.pda.okhttp.bean.RequestMethod;
import com.sgcc.pda.sdk.utils.DataConversionUtil;
import com.sgcc.pda.sdk.utils.ZoomSPUtils;
import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;

import static com.sgcc.pda.sdk.utils.ConstantSM4.SM4_IV;
import static com.sgcc.pda.sdk.utils.ConstantSM4.SM4_KEY;

/**
 * Created by cj on 2020/9/1.
 * 为业务app请求，提供统一通用的Model
 */
public class PostDataWeaveStringModel extends HzBaseHttpModel<PostDataWeaveStringRequest, String> {

    private String tag;

    @Override
    protected OkHttpRequestEntity handleInput(PostDataWeaveStringRequest input) {

        String ip = getIP();
        int port = getPort();
        String url = "http://" + ip + ":" + port + "/eomfront/FrontSys/" + input.getUri();

        tag = input.getServerMethod();

        ApiGateRequestBean apiGagtRequestBean = createApiGagtRequestBean(input);

        OkHttpRequestEntity okHttpRequestEntity = new OkHttpRequestEntity("")
                .url(url)
                .requestMethod(RequestMethod.POST)
                .addHead("Content-Type", "multipart/form-data")
                .addParam("SERVER_NAME", apiGagtRequestBean.getSERVER_NAME())
                .addParam("REQUEST_PARM", apiGagtRequestBean.getREQUEST_PARM());
        if(ZoomSPUtils.getEncryption()){
            String request_parm = apiGagtRequestBean.getREQUEST_PARM();
            try {
                String dataCbc = SM4Utils.encryptData_CBC(SM4_KEY, SM4_IV, request_parm);
                okHttpRequestEntity.addParam("REQUEST_PARM",dataCbc);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (input.isNeedUid()) {
            okHttpRequestEntity.addParam("UID", apiGagtRequestBean.getUID());
            okHttpRequestEntity.addParam("MAC", apiGagtRequestBean.getMAC());
        }

        return okHttpRequestEntity;
    }

    private ApiGateRequestBean createApiGagtRequestBean(PostDataWeaveStringRequest input) {
        String params = createParams(input.getServerMethod(), input.getRequestParams());
        String requestParam = str2HexStr(params);

        ApiGateRequestBean bean = new ApiGateRequestBean();
        bean.setUID(input.getUid());
        bean.setSERVER_NAME(input.getServerName());
        bean.setREQUEST_PARM(requestParam);
        bean.setMAC("12345");
        return bean;

    }

    @Override
    protected String handleOutput(String result) {
        if (ZoomSPUtils.getEncryption()) {
            try {
                result = SM4Utils.decryptData_CBC(SM4_KEY, SM4_IV, result);
                result = DataConversionUtil.hexStr2Str(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    @Override
    public void request(PostDataWeaveStringRequest request) {
        super.request(request);
    }


    /**
     * 获取IP地址
     */
    public String getIP() {
        Context context = ZoomApplication.getInstance();
        String ip;
        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            ip = SharepreferenceUtil.getCommIpUSB(context);
        } else {
            ip = SharepreferenceUtil.getCommIp(context);
        }
        return ip;
    }

    /**
     * 获取端口号
     */
    public int getPort() {
        Context context = ZoomApplication.getInstance();
        String port;
        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            port = SharepreferenceUtil.getCommPortUSB(context);
        } else {
            port = SharepreferenceUtil.getCommPort(context);
        }
        return Integer.parseInt(port);
    }

    /**
     * 为get请求组装url，将参数追加到method?后面。
     * url可以是方法名method，也可以是method?key1=value1
     */
    public String createParams(String url, Map<String, String> params) {
        Uri.Builder urlBuilder = Uri.parse(url).buildUpon();
        Iterator<Map.Entry<String, String>> paramIterator = params.entrySet().iterator();
        while (paramIterator.hasNext()) {
            Map.Entry<String, String> entry = paramIterator.next();
            urlBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
        }
        String origionUrl = urlBuilder.build().toString();
        try {
            //@会变成%40，需要解码。
            origionUrl = URLDecoder.decode(origionUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return origionUrl;
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @param str 待转换的ASCII字符串
     * @return HexString
     */
    public static String str2HexStr(String str) {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString().trim();
    }


    public void cancelRequest() {
        super.cancelRequest(tag);
    }
}
